import Vue from 'vue'
import Vuex from 'vuex'

import depart from './depart'

import {
  getMenu,
} from '@/api/public.js'
import {
  setAuth,
  cleanAuth,
  getDepartId,
  getUser,
} from '@/utils/auth.js'
import {
  filterMenu,
} from '@/utils/menus.js'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    depart,
  },
  state: {
    ifInit: false,
    ifAuth: false,
    departId: null,
    user: null,
    isCollapsed: false,
    routers: [],
    menusLeft: [],
    btnShow: sessionStorage.getItem('btnShow'),
    cutPageM: sessionStorage.getItem('cutPageM'),
    tableId: sessionStorage.getItem('tableId'),
    sortId: sessionStorage.getItem('sortId'),
    isShow: false,
    permissions:JSON.parse(window.localStorage.getItem('logo'))||[],
    areaType: sessionStorage.getItem('areaType'),
  },
  actions: {
    async checkInit ({
      state,
    }) {
      const { success, data } = await getMenu()
      let routers = []
      let departId = null
      let user = null
      if (success) {
        state.ifInit = true
        routers = filterMenu(data.router)
        console.log('vuex====', data.router)

        console.log('vuex====', routers)

        departId = getDepartId()
        user = getUser()
      }
      state.routers = routers
      state.departId = departId
      state.user = user
      return success
    },
    async initAuth ({
      state,
      dispatch,
    }, payload) {
      /* eslint-disable-next-line */
      console.log('payload=====',payload)
      const { access_token, departId, user, companyName, logo, menus} = payload
      // const { access_token, departId, user, departName, logo, menus} = payload
      state.user = user
      state.departId = departId
      state.companyName = companyName
      // state.departName = departName
      state.logo = logo
      state.ifAuth = true
      state.menusLeft = menus
      setAuth({
        access_token,
        departId,
        user,
        // departName,
        companyName,
        logo,
        menus,
      })
      const success = await dispatch('checkInit')
      return success
    },
    async resetAuth ({
      state,
    }) {
      cleanAuth()
      state.ifAuth = false
      state.departId = null
      state.user = null
      state.routers = []
    },
  },
  getters: {
    permissions:  (state, getters) =>{
        return state.permissions
    }
  },
  mutations: {
    collapsedSider (state) {
      state.isCollapsed = !state.isCollapsed
    },
  },
})
